package com.cbnu.SmartCampusLife;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;

public class Map extends MapActivity implements LocationListener {
    /** Called when the activity is first created. */
	

	private String lecSum[][] = new String[3][12];
	private String lecLoc = null;
	private int stuIdChk = 0;
	
	private double uniLat = 36.629057;
	private double uniLon = 127.456335;
	private double latitude = 0;
	private double longitude = 0;
	private GeoPoint myLoc;
	
	private MapController mc = null;
	private MapView mapView;
	private MyLocation mLocation;
	private LocationManager myLocationManager;
	private Criteria criteria;
	
	private boolean fromTimeTableCheck = false;
	private ImageView mapMarker;
    private RelativeLayout rl;
    private String selectedBuildName = null;
	
    //Building Information
	private String[][] buildName = {
							{"N1", "20"}, {"N2", "N2"},
							{"N3", "197"}, {"N4", "605"},
							{"N5", "604"}, {"N6", "603"},
							{"N7", "601"}, {"N8", "602"}, 
							{"N9", "606"}, {"N10", "1"}, 
							{"N11", "52"}, {"N12", "39"}, 
							{"N13", "59"}, {"N14", "56"}, 
							{"N15", "57"}, {"N16-1", "58"}, 
							{"N16-2", "65A"}, {"N16-3", "65"}, 
							{"N17-1", "198"}, {"N17-2", "66"}, 
							{"N17-3", "67"}, {"N17-4", "68"}, 
							{"N17-5", "69"}, {"N17-6", "503"}, 
							{"N18", "64"}, {"N19", "63"}, 
							{"N20-1", "62"}, {"N20-2", "61"}, 
							{"N21", "70"}, {"E1-1", "82"}, 
							{"E1-2", "81"}, {"E2", "501"}, 
							{"E3", "38"}, {"E4-1", "75"}, 
							{"E4-2", "76"}, {"E4-3", "74"}, 
							{"E5", "85"}, {"E6", "136"}, 
							{"E7-1", "150"}, {"E7-2", "160"}, 
							{"E7-3", "151"}, {"E8-1", "44"}, 
							{"E8-2", "45"}, {"E8-3", "46"}, 
							{"E8-4", "47"}, {"E8-5", "48"}, 
							{"E8-6", "49"}, {"E8-7", "50"}, 
							{"E8-8", "51"}, {"E8-9", "195"}, 
							{"E8-10", "508"}, {"E9", "192"}, 
							{"E10", "193"}, {"E11-1", "141"}, 
							{"E11-2", "142"}, {"E11-3", "145"}, 
							{"E11-4", "142"}, {"E11-5", "143"}, 
							{"E12-1", "507"}, {"E12-2", "194"}, 
							{"E12-3", "506"}, {"S1-1", "40"}, 
							{"S1-2", "41"}, {"S1-3", "42"}, 
							{"S1-4", "43"}, {"S1-5", "37"}, 
							{"S1-6", "36"}, {"S2", "32"}, 
							{"S3", "31"}, {"S4-1", "21"}, 
							{"S4-2", "502"}, {"S5-1", "104"}, 
							{"S5-2", "14"}, {"S6-1", "186"}, 
							{"S6-2", "199"}, {"S7-1", "13"}, 
							{"S7-2", "12"}, {"S8", "505"}, 
							{"S9", "33"}, {"S10", "181"}, 
							{"S12", "183"}, {"S13", "126"}, 
							{"S14", "3"}, {"S15", "4"}, 
							{"S16", "124"}, {"S17-1", "9"}, 
							{"S17-2", "9"}, {"S17-3", "9"}, 
							{"S17-4", "8"}, {"S17-5", "5"}, 
							{"S17-6", "7"}, {"S17-7", "6"}, 
							{"S18", "123"}, {"S19", "401"}, 
							{"S20", "S20"}, {"S21-1", "90"}, 
							{"S21-2", "187"}, {"S21-3", "504"}, 
							{"S21-4", "92"}, {"S21-5", "91"}, 
							
							};
	private double[][] buildLoc = {
									{36.632026, 127.452800}, {36.632112, 127.453669},
									{36.631169, 127.454903}, {36.632482, 127.455236},
									{36.632021, 127.455896}, {36.632452, 127.455488},
									{36.632844, 127.455997}, {36.633085, 127.456534},
									{36.633265, 127.457070}, {36.630278, 127.454742},
									{36.629339, 127.455246}, {36.628461, 127.457403},
									{36.630063, 127.456899}, {36.630958, 127.456512},
									{36.629391, 127.457843}, {36.629916, 127.458926},
									{36.629916, 127.458926}, {36.629916, 127.458926},
									{36.629916, 127.458926}, {36.631569, 127.457553},
									{36.631569, 127.457553}, {36.631199, 127.458133},
									{36.631449, 127.458347}, {36.631810, 127.458562},
									{36.630906, 127.459356}, {36.630571, 127.459860},
									{36.630355, 127.460879}, {36.630571, 127.459860},
									{36.629899, 127.460192}, {36.629004, 127.460804},
									{36.628521, 127.460343}, {36.628220, 127.459313},
									{36.627635, 127.458669}, {36.627230, 127.460632},
									{36.626507, 127.462306}, {36.626842, 127.462488},
									{36.627075, 127.461727}, {36.628005, 127.462145},
									{36.625051, 127.460997}, {36.624664, 127.460686},
									{36.625577, 127.460289}, {36.626696, 127.458272},
									{36.626343, 127.457725}, {36.626042, 127.458862},
									{36.625387, 127.458991}, {36.625034, 127.458830},
									{36.624586, 127.458572}, {36.625465, 127.457939},
									{36.624543, 127.459205}, {36.625163, 127.459248},
									{36.624121, 127.458068}, {36.625138, 127.457188},
									{36.624871, 127.457778}, {36.624208, 127.457403},
									{36.624001, 127.457231}, {36.624044, 127.457521},
									{36.623605, 127.457682}, {36.623777, 127.456985},
									{36.623390, 127.455890}, {36.623484, 127.456813},
									{36.623484, 127.456813}, {36.627738, 127.456727},
									{36.627118, 127.456888}, {36.626679, 127.456877},
									{36.626240, 127.456706}, {36.625585, 127.455879},
									{36.625112, 127.455997}, {36.626429, 127.455461},
									{36.626283, 127.454699}, {36.625594, 127.454367},
									{36.625241, 127.454807}, {36.625112, 127.453691},
									{36.624836, 127.453637}, {36.625336, 127.453337},
									{36.625206, 127.453122}, {36.625844, 127.453787},
									{36.625990, 127.453755}, {36.627187, 127.454141},
									{36.627695, 127.455407}, {36.627970, 127.455482},
									{36.628298, 127.454989}, {36.628151, 127.454517},
									{36.627695, 127.455397}, {36.627781, 127.453605},
									{36.628031, 127.453669}, {36.627970, 127.452403},
									{36.627350, 127.452736}, {36.627290, 127.452178},
									{36.627342, 127.451255}, {36.627325, 127.450451},
									{36.627040, 127.450955}, {36.627049, 127.450408},
									{36.628504, 127.451416}, {36.628659, 127.451599},
									{36.628676, 127.452146}, {36.628806, 127.452371},
									{36.629004, 127.451491}, {36.629219, 127.451556},
									{36.629331, 127.452832}, {36.630097, 127.453079}
									};
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);      
		
		lecSum[0] = getIntent().getStringArrayExtra("lecSum[0]");
		lecSum[1] = getIntent().getStringArrayExtra("lecSum[1]");
		for(int i = 0; i < lecSum[1].length; i++) 	{
			if(lecSum[1][i] != null) {
				if(lecSum[1][i].matches("학연...")) lecSum[1][i] = lecSum[1][i].substring(0, lecSum[1][i].length() - 3);
				else {
					lecSum[1][i] = lecSum[1][i].replaceAll("\\(.*",  "");
					lecSum[1][i] = lecSum[1][i].substring(0, lecSum[1][i].length() - 4);
				}
			}
		}
		lecSum[2] = getIntent().getStringArrayExtra("lecSum[2]");
		lecLoc = getIntent().getStringExtra("lecLoc");
		// 0 : Use new building name from MainMenu, 1 : Use old building name from MainMenu
		// 2 : Use new building name from TimeTable, 3 : Use old building name from TimeTable
        stuIdChk = getIntent().getIntExtra("stuIdChk", 0);
		
        mapView = (MapView) findViewById(R.id.mapView);
        mapView.setBuiltInZoomControls(true);
        mc = mapView.getController();
        mc.setZoom(17);
        mc.setCenter(new GeoPoint((int)(uniLat * 1E6), (int)(uniLon * 1E6)));
        myLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setPowerRequirement(Criteria.POWER_HIGH);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 1, this);
        Location location = myLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        
        if(location == null) {
        	Log.d("GPS Fail", "Try Network provider");
        	location = myLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
        if(location == null) {
        	Log.d("Network Fail", "Go to center of CBNU");
        	Toast.makeText(this, "위치 서비스를 이용할 수 없습니다. 사용자의 위치가 학교 중앙으로 인식합니다.", Toast.LENGTH_SHORT).show();
        	myLoc = new GeoPoint((int)(uniLat * 1E6), (int)(uniLon * 1E6));
        }
        else myLoc = new GeoPoint((int)(location.getLatitude() * 1E6), (int)(location.getLongitude() * 1E6));
		Log.d("MyLocation", myLoc.getLatitudeE6() + ", " + myLoc.getLongitudeE6());
		
		GeoPoint geoPoint;
        mLocation = new MyLocation(Map.this, mapView);
		
        for(int i = 0; i < buildLoc.length; i++) {
            latitude = buildLoc[i][0];
            longitude =  buildLoc[i][1];
            geoPoint = new GeoPoint((int)(latitude * 1E6), (int)(longitude * 1E6));
            for(int a = 0; a < 12; a++) {
            	if(lecSum[1][a] == null) break;
            	else if(lecSum[1][a] != null && lecSum[1][a].equals(buildName[i][0])) {
            		if(lecLoc != null && lecLoc.substring(0, lecLoc.indexOf("\n")) != null) {
            			if(lecLoc.substring(0, lecLoc.indexOf("\n")).equals(lecSum[0][a])) {
            				Toast toast = Toast.makeText(Map.this, lecLoc, Toast.LENGTH_SHORT);
            				LinearLayout toastView = new LinearLayout(this);
            				toastView.setOrientation(1);
            				toastView.setBackgroundColor(Color.BLACK);
            				toastView.setPadding(4, 4, 4, 4);
            				TextView tv = new TextView(Map.this);
            				tv.setText(lecLoc);
            				tv.setGravity(Gravity.CENTER);
            				tv.setTextColor(Color.WHITE);
            				toastView.addView(tv);
            				toast.setView(toastView);
            				toast.show();
            				mc.animateTo(geoPoint);
            				fromTimeTableCheck = true;
            			}
                    }
            	}
            }
            RelativeLayout buildMarkerLayout = new RelativeLayout(this);
            TextView tvv = new TextView(this);
            if(stuIdChk == 1 || stuIdChk == 3) tvv.setText( buildName[i][1]);
            else tvv.setText( buildName[i][0]);
            tvv.setTextColor(Color.BLACK);
            tvv.setTextSize(9);
            tvv.setGravity(Gravity.CENTER);
            tvv.setBackgroundResource(R.drawable.circle);
            tvv.setTypeface(null, Typeface.BOLD);
            buildMarkerLayout.addView(tvv);
            MapView.LayoutParams llMarkerParams = new MapView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, new GeoPoint((int)(latitude * 1E6) + 60, (int)(longitude * 1E6)), MapView.LayoutParams.BOTTOM_CENTER);
            mapView.addView(buildMarkerLayout, llMarkerParams);
            buildMarkerLayout.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					RelativeLayout selectedView = (RelativeLayout)v;
					TextView selectedTextView =(TextView) selectedView.getChildAt(0);
					String[] str = new String[12];
					int length = 0;
					double l1 = 0;
					double l2 = 0;
					boolean dupl = false;
					if(stuIdChk == 1 || stuIdChk == 3) {
						for(int i = 0; i < buildName.length; i++) {
							if(selectedTextView.getText().toString().equals(buildName[i][1])) {
								if(selectedBuildName != null && (selectedBuildName.equals(buildName[i][0]) || selectedBuildName.equals(buildName[i][1]))) {
									dupl = true;
									break;
								}
								selectedBuildName = buildName[i][0];
								l1 = buildLoc[i][0];
								l2 = buildLoc[i][1];
								break;
							}
						}
					}
					if(dupl) {
						mapView.removeView(rl);
						selectedBuildName = null;
					}
					else {
						for(int i = 0; i < 12; i++) {
							if(lecSum[1][i] != null && selectedBuildName.equals(lecSum[1][i])) {
								str[length++] =  lecSum[2][i] + ") " +  lecSum[0][i];
							}
						}
						mapView.removeView(rl);
			            rl = new RelativeLayout(Map.this);
			            TextView tvv = new TextView(Map.this);
			            String temp = new String();
			            for(int i = 0; i < length; i++) {
			            	if(str[i] != null) temp += str[i];
			            	if(i != length - 1) temp += "\n";
			            }
			            if(temp.length() != 0) {
			            	tvv.setText(temp);
			            	tvv.setTextColor(Color.BLACK);
				            tvv.setTextSize(9);
				            tvv.setGravity(Gravity.CENTER);
				            tvv.setBackgroundResource(R.drawable.balloon);
				            tvv.setTypeface(null, Typeface.BOLD);
				            rl.addView(tvv);
				            MapView.LayoutParams llMarkerParams = new MapView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, new GeoPoint((int)(l1 * 1E6), (int)(l2 * 1E6)), MapView.LayoutParams.BOTTOM_CENTER);
				            mapView.addView(rl, llMarkerParams);
			            }
			            else mapView.removeView(rl);
					}
				}
			});
            if(stuIdChk <= 2){
            	mc.animateTo(myLoc);
    		}
        }
        //Check all of provider. If not be able to use provider, Go to center of CBNU
		MapView.LayoutParams mapMarkerParams = new MapView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, myLoc, MapView.LayoutParams.BOTTOM_CENTER);
        mapMarker = new ImageView(getApplicationContext());
        mapMarker.setImageResource(R.drawable.mylocation);
        mapView.addView(mapMarker, mapMarkerParams);
	}
	
	public class MyLocation extends MyLocationOverlay {
		public MyLocation(Context context, MapView mapview) {
			super(context, mapView);
		}
		@Override
		protected boolean dispatchTap() {
			return false;
		}
	}
	
	public void onLocationChanged(Location location) {
		mapView.removeView(mapMarker);
		myLoc = new GeoPoint((int)(location.getLatitude() * 1E6), (int)(location.getLongitude() * 1E6));
		Log.d(" UserLog : MyLocation(onLocationChanged)", myLoc.getLatitudeE6() + ", " + myLoc.getLongitudeE6());
		MapView.LayoutParams mapMarkerParams = new MapView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, myLoc, MapView.LayoutParams.BOTTOM_CENTER);
        mapMarker = new ImageView(getApplicationContext());
        mapMarker.setImageResource(R.drawable.mylocation);
        mapView.addView(mapMarker, mapMarkerParams);
        if(!fromTimeTableCheck){
        	mc.animateTo(myLoc);
		}
	}

	public void onProviderDisabled(String provider) {
		
	}

	public void onProviderEnabled(String provider) {
		
	}

	public void onStatusChanged(String provider, int status, Bundle extras) {
		
	}
	
    
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	
	@Override
	public void onResume() {
		super.onResume();
		Log.d("onResume", "onResume");
		mLocation.enableMyLocation();
		mLocation.enableCompass();
	}
	
	@Override
	public void onPause() {
		super.onPause();
		Log.d("onPause", "onPause");
		mLocation.disableMyLocation();
		mLocation.disableCompass();
	}
	
	//Finish Event
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
    	if(keyCode == KeyEvent.KEYCODE_BACK) finish();
    	return super.onKeyDown(keyCode, event);
    }
	public class buildMarker {
		RelativeLayout  buildMarkerLayout;
		TextView buildMarkerTextView;
	}
}